package com.example.gateway.security;


import io.jsonwebtoken.Jwts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

/**
 * 验证token工具类
 */
public class JwtUtils {

    private static Logger log = LoggerFactory.getLogger(JwtUtils.class);

    //公钥
    private static String rsa_public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDWSb3s82ylSxIa9Xqasz2dBPMHETN//+cGCCwYDour49LyeJMmo53KT7f4WKzhdKHWkzaxCnVCSOGR7pogga3hP4I5Qe6xILJrkQ8+L3bwpYwUMm++f43ltXYUPrblAlSOFqTe89DwEPjTa/pCpbd7P6HLXi22fxMX+0ay4vAHwQIDAQAB";

    /**
     * 如果使用非对称加密算法 RSA
     * 字符串转公钥
     * @return
     */
    private static PublicKey stringToPubKey(String rsa_public_key){
        PublicKey publicKey = null;
        try {
            X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(new BASE64Decoder().decodeBuffer(rsa_public_key));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            publicKey = keyFactory.generatePublic(bobPubKeySpec);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        System.out.println("公钥对象--：" + publicKey);
        return publicKey;
    }

    /**
     * 验签
     * 解密token 返回payload的信息主体对象claims
     * @param jwtToken token
     * @return Claims
     */
    public static boolean validateJWT(String jwtToken){
        try {
            PublicKey publicKey = stringToPubKey(rsa_public_key);
            String u = Jwts.parser()
                    .setSigningKey(publicKey)
                    .parseClaimsJws(jwtToken).getBody().getSubject();  //得到主体
//                    JwsHeader header = Jwts.parser()
//                            .setSigningKey(publicKey)
//                            .parseClaimsJws(jwtToken).getHeader();  //得到头部
//                    String signature = Jwts.parser()
//                    //        .setSigningKey(generalKey())
//                            .setSigningKey(publicKey)
//                            .parseClaimsJws(jwtToken).getSignature();  //得到签名
//                    System.out.println("认证类型 -- " + header.get("typ"));
//                    System.out.println("算法 -- " + header.get("alg"));
//                    System.out.println("签名 -- ：" + signature);

            if(u != null && !"".equals(u)){
                log.info("验签成功！");
//                log.info("header--:" + header.toString());
//                log.info("算法--："+header.getAlgorithm());
//                log.info("类型--："+header.getType());
                log.info("获取用户信息为--："+ u);
                return true;
            }
            return false;
        }catch(Exception e){
            log.error("验签失败："+e.getMessage());
            return false;
        }
    }


    /**
     * 测试验证token
     * @param args
     */
    public static void main(String[] args) {
        //验证token
        validateJWT("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ7XCJ1c2VyTmFtZVwiOlwibWhnXCIsXCJ1c2VySWRcIjpcIjEyM1wifSIsImV4cCI6MTYzMTI0NTQyMX0.dZqhrkV6g6Xjq7XhbNIjYbwYVOiT1LKlx6QeBw9hYvfTXniskFXaGb0nSooSsbUKgVebiSbrmTerfqlA2fXnTVPMJswYBmL32QOXHpMQzFgMedQO4Mm3FGFBgfBV_e5ExujWtJWW3nHrYXVi8ig6Ht3_CFfvvwhcWwrftW7-3SI");

    }





}
